package spittr.service;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import spittr.model.User;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserService {
    Map<String,User> userMap = new HashMap<>();

    public void addUser(MultipartFile headPicture,String uploadPath, User user){
        if(!userMap.containsKey(user.getUsername())) {
            userMap.put(user.getUsername(),user);
            try {
                if(!headPicture.isEmpty()){
                    String contentType = headPicture.getContentType();
                    String fileType = contentType.substring(contentType.lastIndexOf("image/")+6);
                    File file = new File(uploadPath+"/imgs/"+user.getUsername()+"."+fileType);
                    FileUtils.writeByteArrayToFile(file, headPicture.getBytes());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public User findUser(String username){
        return userMap.get(username);
    }
}
